
const createError = (p:any)=>{}
const defineEventHandler = (p:any)=>{}
const sendError = (p:any, o:any)=>{}

/**
 * NodeJS脚本，检测恶意请求IP的路径；案例Nuxt3
 */

// 禁止访问的文件后缀
const dangerFileSuffixRegexp = /\.(php|asp|aspx|jsp|cgi|pl|py|sh|bat|exe|dll|cmd|bin|sql|log|env|ini|conf|cfg|bak|tar|gz|zip|rar|do|class)(\?|$)/i;
// 拦截敏感目录
const dangerSubPathRegexp = /\/(admin|backup|config|db|test|tmp|logs|sql|upload|wp-admin|phpmyadmin|jmx-console|web-console)\/$/;
// 敏感词
const dangerousKeyWordsRegexp = /(bash|cmd|delete|exec|getenv|kill|password|root|run|select|shell|sudo|system|truncate|union|update|wget|xp_cmdshell)/i;

enum DANGERE_NUM {
	SUFFIX = '文件后缀不合法',
	SUBPATH = '敏感路径',
	KEYWORDS = '敏感词',
}

// 记录异常日志
const recordAttackLog = (ip:string, path:string, type: DANGERE_NUM)=>{
	console.log(`Attack![${new Date().toLocaleString()}]异常访问记录: 记录类型 ${type}, 访问ip ${ip}, 访问路径 ${path}`);
}

// 检验安全正则，平均消耗时间不足1ms
export default defineEventHandler((event) => {
	const path = event.path;
	const sourceIP = event.headers.get('x-forwarded-for')||event.node.req.socket.remoteAddress||'unknow';
	if(dangerFileSuffixRegexp.test(path)){
		recordAttackLog(sourceIP, path, DANGERE_NUM.SUFFIX);
		sendError(event, createError({
			statusCode: 403,
			statusMessage: '禁止访问, 你太年轻了',
			message: '禁止访问, 你太年轻了',
		}));
	}else if(dangerSubPathRegexp.test(path)){
		recordAttackLog(sourceIP, path, DANGERE_NUM.SUBPATH);
		sendError(event, createError({
			statusCode: 403,
			statusMessage: '禁止访问, 你太年轻了',
			message: '禁止访问, 你太年轻了',
		}));
	}else if(dangerousKeyWordsRegexp.test(path)){
		recordAttackLog(sourceIP, path, DANGERE_NUM.KEYWORDS);
		sendError(event, createError({
			statusCode: 403,
			statusMessage: '禁止访问, 你太年轻了',
			message: '禁止访问, 你太年轻了',
		}));
	}
});
